require 'rubygems'
require 'bit-struct'

require 'milfs/object/interface'

module Mil
  module FS
    # Ruby representation of a binary structure using the BitStruct
    # library.
    #
    # ---
    # *Structure*:: <tt> </tt> 
    # +size+:: <tt>Size of *data</tt>
    # +data+:: <tt>Variable length field containin the data segment of the Block</tt>
    class BlockStruct < BitStruct
      float   :size,	  32,	  "Size of *data"
      rest    :data,		  "Block Contents"
    end

    # A wrapper class to encapsulate the data structure BlockStruct
    # and provide easy access to the structure.
    class Block < Mil::Object::Interface
      def initialize(data_seg = nil)
	@struct = BlockStruct.new

	self.data = data_seg unless data_seg.nil?
      end

      # This method will compare the internal wrapped structure with
      # that of the object passed in.
      def == (object)
	if ( truth = object.is_a? Mil::FS::Block )
	  truth |= @struct.size == object.struct.size
	  truth |= @struct.data == object.struct.data
	end

	truth
      end

      # This method returns a printable string representation 
      # of the wrapped Block structure.
      def dump
        "Block Object of size #{@struct.size}"
      end

      # This method should be overriden to create an instance of the
      # wrapped structure type from the passed string and store it
      # in the @struct variable.
      def struct=(string)
	@struct = BlockStruct.new(string)
      end

      # Store data_seg into the Block.
      def data=(data_seg)
	if @struct
	  @struct.size = data_seg.size
	  @struct.data = data_seg
	else
	  @struct = BlockStruct.new
	  @struct.size = data_seg.size
	  @struct.data = data_seg
	end
      end

      # Retrieve data from the Block.
      def data
	@struct.data
      end

      # Retrieve the size of the Block.
      def size
	@struct.size
      end
    end
  end
end
